package fun.hijklmn.magic.admin.server.pojo;

import fun.hijklmn.magic.admin.common.enums.UserStatusEnum;
import fun.hijklmn.magic.admin.common.pojo.Role;
import fun.hijklmn.magic.admin.common.pojo.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;

/**
 * @Description
 * @Author fs
 * @Date 2021/6/25 17:53
 * @Version 0.0.1-SNAPSHOT
 **/
@Data
public class SysUser implements UserDetails {

    private Role role;

    private User user;

    private Collection<? extends GrantedAuthority> authorities;

    public SysUser(User user, Role role) {
        this.user = user;
        this.role = role;
        authorities = Collections.singleton(new SimpleGrantedAuthority(role.getCode()));
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singleton(new SimpleGrantedAuthority(role.getCode()));
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return UserStatusEnum.expire.status().intValue() != user.getStatus();
    }

    @Override
    public boolean isAccountNonLocked() {
        return UserStatusEnum.freeze.status().intValue() != user.getStatus();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return user.getIsDelete() && (UserStatusEnum.normal.status().intValue() == user.getStatus());
    }

    @Override
    public String toString() {
        return "SysUser{" +
                "role=" + role +
                ", user=" + user +
                ", authorities=" + authorities +
                '}';
    }
}
